

from fontTools.ttLib.ttFont import TTFont
import re
from bs4 import BeautifulSoup
import requests



def takeXY(points):
    pts = points.find_all('pt')
    x = []
    y = []
    for pt in pts:
        x.append(re.findall('x="(.*?)"', str(pt))[0])
        y.append(re.findall('y="(.*?)"', str(pt))[0])
    x_str = ','.join(x)
    y_str = ','.join(y)
    return (x_str, y_str)

def findOneValue(key, d):
    for k, v in d.items():
        if key == k:
            return v
    return False

def getFontsInfo(link):
    herder = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'en',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'
    }
    r = requests.get(link, headers=herder)
    url_shopNum = 'http:'+re.findall(r'format.*url\("(.*?)"\);} .shopNum', r.text)[0]
    url_address= 'http:'+re.findall(r'format.*url\("(.*?)"\);} .address', r.text)[0] #暂时可以获取地址
    shopNum=re.split('/|\.',url_shopNum)[-2]
    address=re.split('/|\.',url_address)[-2]

    fontsinfo={shopNum:url_shopNum,address:url_address}
    return fontsinfo,shopNum


def downloadFonts(name,url):
    herder = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'en',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'
    }
    r = requests.get(url, headers=herder)

    fp = open(f"./woff_fonts/{name}.woff", "wb")
    fp.write(r.content)
    fp.close()
    print('Finsh downloadFonts')


def dealFonts(name):
    with open('./base_font/font_dazhongdianping.txt','r') as f:
        base=eval(f.read())
    first_name=name.split('.')[0]
    font=TTFont(f'./woff_fonts/{first_name}.woff')
    font.saveXML(f'./woff_fonts/{first_name}.xml')
    with open(f'./woff_fonts/{first_name}.xml',encoding='utf-8') as f:
        font_text=f.read()
    f.close()

    soup=BeautifulSoup(font_text,'xml')
    names_1=font.getGlyphNames()
    str_points_1=soup.find_all('TTGlyph')

    font_dict={}
    for n,s in zip(names_1,str_points_1):
        if n[:3]=='uni':
            base_key=takeXY(s)
            value=findOneValue(base_key,base)
            if value:
                key=n[3:]
                font_dict[key]=value

    with open(f'./fonts_dicts/{first_name}.txt','w') as f:
        f.write(str(font_dict))
    f.close()
    print('Finsh deal fonts')



